﻿using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour 
{
	public PlayerStateController.playerState currentPlayerState = PlayerStateController.playerState.idle;
	public GameObject PlayerObject = null;
	public float CameraTrackingSpeed = 0.2f;
	private Vector3 lastTargetPosition = Vector3.zero;
	private Vector3 currTargetPosition = Vector3.zero;
	private float currLerpDistance = 0.0f;

	void Start()
	{
		Vector3 playerPos = PlayerObject.transform.position;
		Vector3 cameraPos = transform.position;
		Vector3 startTargetPos = playerPos;

		startTargetPos.z = cameraPos.z;
		lastTargetPosition = startTargetPos;
		currTargetPosition = startTargetPos;
		currLerpDistance = 1.0f;
	}

	void OnEnable()
	{
		PlayerStateController.onStateChange += onPlayerStateChange;
	}

	void OnDisable()
	{
		PlayerStateController.onStateChange += onPlayerStateChange;
	}

	void onPlayerStateChange(PlayerStateController.playerState newState)
	{
		currentPlayerState = newState;
	}

	void LateUpdate()
	{
		onStateCycle();

		currLerpDistance += CameraTrackingSpeed;
		transform.position = Vector3.Lerp (lastTargetPosition, currTargetPosition, currLerpDistance);
	}

	void onStateCycle()
	{
		switch (currentPlayerState) 
		{
		    case PlayerStateController.playerState.idle:
				TrackPlayer();
			break;

			default:
				TrackPlayer();
			break;
		}
	}

	void TrackPlayer()
	{
		Vector3 currCamPos = transform.position;
		Vector3 currPlayerPos = PlayerObject.transform.position;

		if (currCamPos.x == currPlayerPos.x && currCamPos.y == currPlayerPos.y) 
		{
			currLerpDistance = 1f;
			lastTargetPosition = currCamPos;
			currTargetPosition = currCamPos;
			return;
		}

		currLerpDistance = 0f;
		lastTargetPosition = currCamPos;
		currTargetPosition = currPlayerPos;
		currTargetPosition.z = currCamPos.z;
	}

	void StopTrackingPlayer()
	{
		Vector3 currCamPos = transform.position;
		currTargetPosition = currCamPos;
		lastTargetPosition = currCamPos;

		currLerpDistance = 1.0f;
	}
}